package com.park.controller;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.park.model.Activemq;
import com.park.model.BusinessCarport;
import com.park.model.Constants;
import com.park.model.Device;
import com.park.model.Hardware;
import com.park.model.Hardwareinfo;
import com.park.model.Park;
import com.park.model.Picdata;
import com.park.model.Root;
import com.park.service.BusinessCarportService;
import com.park.service.HardwareInfoService;
import com.park.service.HardwareService;
import com.park.service.ParkService;
import com.park.service.Utility;
import net.sf.json.groovy.GJson;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Controller
@RequestMapping("YNVideoPile")
public class YNVideoPileController {
	@Autowired
	private ParkService parkService;
	@Autowired
	private BusinessCarportService businessCarportService;
	
	@Autowired
	private HardwareService hardwareService;
	
	@Autowired
	private HardwareInfoService hardwareInfoService;

	private static Log logger = LogFactory.getLog(YNVideoPileController.class);
	//注册
	@RequestMapping(value = "login", method = RequestMethod.POST, produces = {"application/json;charset=utf-8" })
	@ResponseBody
	public String Login(@RequestBody Map<String, Object> args) {
		Map<String, Object> result=new HashMap<>();
		logger.info("cmd:"+args);
		String cmd=(String)args.get("cmd");
		if(args.isEmpty()){
			result.put("msg", "失败");
			result.put("response", "0");
			result.put("reason", 0);
		}else{
			result.put("msg", "成功");
			result.put("response", "1");
			result.put("body", args);
		}

		return Utility.gson.toJson(result);
	}
	//心跳
	@RequestMapping(value = "heartbeat", method = RequestMethod.POST, produces = {"application/json;charset=utf-8" })
	@ResponseBody
	public String Heartbeat(@RequestBody Map<String, Object> args) {
		Map<String, Object> result=new HashMap<String, Object>();
		logger.info("cmd:"+args);
		String cmd=(String)args.get("cmd");
		if(cmd.equals("sendDeviceHeartbeat")){
			result.put("msg", "成功");
			result.put("response", "1");
			result.put("body", args);
		}
		return Utility.gson.toJson(result);
	}
	//停车
	@RequestMapping(value = "/parking", method = RequestMethod.POST, produces = {"application/json;charset=utf-8" })
	@ResponseBody
	public String Parking(@RequestBody Map<String, Object> args) {
		Map<String, Object> result=new HashMap<String, Object>();
		//Gson gson=new Gson();
		logger.info("cmd:"+args.toString());
		String cmd=(String)args.get("cmd");
		Gson gson=new Gson();
		String json=gson.toJson(args);//序列化
		Root ro=gson.fromJson(json, Root.class);//反序列化
		System.out.println(Arrays.asList(ro));

		String sendInfo = "{\"id\":6547935,\"plateNumber\":\"苏E88888\",\"parkId\":248,\"parkDesc\":\"微信支付停车场-临停车\","
				+ "\"rejectReason\":\"\",\"payType\":2,\"actionType\":\"notify\",\"operatorId\":\"operator\",\"posId\":\"99991111\",\"parkingType\":9,\"chargeMoney\":0.0,\"paidMoney\":0.0,\"isLargeCar\":0,\"entranceDate\":\"2019-06-21 14:17:46\",\"exitDate\":\"2019-06-25 14:17:46\",\"url\":\"\",\"discount\":0.0,\"outUrl\":\"\",\"leftCount\":6,\"mac\":\"99991111,\"\"cmd\":\"01002\",\"\"portNumber\":28}";
		try {
			String url = "http://parkserver.iotclouddashboard.com/parkServer/mq/topicData";
			String data = "{\"id\":6606086,\"plateNumber\":\"苏Z88988\",\"parkId\":248,\"parkDesc\":\"微信支付停车场-临停车\",\"rejectReason\":\"\",\"payType\":2,\"notify\":\"in\",\"operatorId\":\"operator\",\"posId\":\"99990000\",\"parkingType\":9,\"chargeMoney\":0.0,\"paidMoney\":0.0,\"isLargeCar\":0,\"entranceDate\":\"2019-06-23 13:08:29\",\"exitDate\":\"2019-06-21 14:17:46\",\"url\":\"\",\"discount\":0.0,\"outUrl\":\"\",\"leftCount\":2,\"mac\":\"99991111\",\"cmd\":\"01002\",\"portNumber\":28}";
			JSONObject jsons = JSON.parseObject(data);
			String parkId = jsons.get("parkId").toString();
			System.out.println("parkId:"+parkId);
			String mac = jsons.get("mac").toString();
			System.out.println("mac:"+mac);

			MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
			//String requestBody = "I am Jdqm.";

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("mac",mac);
			jsonObject.put("topic",parkId);
			jsonObject.put("data",data);

			Request request = new Request.Builder()
					.url(url)
					.post(okhttp3.RequestBody.create(mediaType, jsonObject.toJSONString()))
					/*.post(okhttp3.RequestBody.create(mediaType, json))*/
					.build();
			OkHttpClient okHttpClient = new OkHttpClient();

			Call call = okHttpClient.newCall(request);
			call.enqueue(new Callback() {

				@Override
				public void onResponse(Call call, Response response) throws IOException {
					// TODO Auto-generated method stub
					logger.info("返回数据"+response.toString());
				}

				@Override
				public void onFailure(Call call, IOException e) {
					// TODO Auto-generated method stub
					logger.info("okHttpPost 请求错误:"+e.getMessage());
				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}

		if(cmd.equals("imgreport")){
			result.put("msg", "成功");
			result.put("response", "1");
			result.put("body", args);
		}else if(cmd.equals("platereport")){
			result.put("msg", "成功");
			result.put("response", "1");
			result.put("body", args);
		}
		logger.info("exitcmd：");
		return Utility.gson.toJson(result);
	}

	//报警
	@RequestMapping(value = "alarm", method = RequestMethod.POST, produces = {"application/json;charset=utf-8" })
	@ResponseBody
	public String alarm(@RequestBody Map<String, Object> args) {
		Map<String, Object> result=new HashMap<String, Object>();
		logger.info("cmd:"+args.toString());
		String cmd=(String)args.get("cmd");
		Gson gson=new Gson();
		String json=new Gson().toJson(args);
		Picdata ro=gson.fromJson(json, Picdata.class);
		System.err.println("body:==========="+ro);
		if(cmd.equals("alarmreport")){
			result.put("msg", "成功");
			result.put("response", "1");
			result.put("body", ro);
		}else if(cmd.equals("manualsnapctrl")){
			result.put("msg", "成功");
			result.put("response", "1");
			result.put("body", ro);
		}
		logger.info("exitcmd:");
		return Utility.gson.toJson(result);
	}
	
	//地磁
	@RequestMapping(value = "GeomagnetismHeartbeat", method = RequestMethod.POST, produces = {"application/json;charset=utf-8" })
	@ResponseBody
	public String GeomagnetismHeartbeat(@RequestBody JSONObject args) throws InterruptedException {
		Map<String, Object> argMap=new HashMap<>();
		logger.info("cmd[入参:]"+args);
		String cmd = (String) args.get("cmd");
		if(cmd.equals("sendDeviceHeartbeat")){//心跳推送
			logger.info("cmd[心跳推送指令:]"+cmd);
			net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(args.get("body"));
			System.out.print("json:"+json);
			String result = json.toString();
			JSONObject bodyJson = JSONObject.parseObject(result);
			Hardwareinfo hwinfo=new Hardwareinfo();
			hwinfo.setMac(String.valueOf(bodyJson.get("deviceID")));
			hwinfo.setMacstatus(String.valueOf(bodyJson.get("parkingStatu")));
			hwinfo.setHeartstatus(String.valueOf(bodyJson.get("time")));
			hwinfo.setParkid(Integer.valueOf(String.valueOf(bodyJson.get("parkID"))));
			List<Hardwareinfo> hw=hardwareInfoService.getByMac(String.valueOf(hwinfo.getMac()));
			logger.info("hw[查询的mac：]"+hwinfo.getMac());
			if(hw==null){
				int heartstatus=hardwareInfoService.insertSelective(hwinfo);
				logger.info("insert[心跳插入:]"+heartstatus);
				if(heartstatus>0){
					argMap.put("code", "100");
					argMap.put("msg", "成功");
				}else{
					argMap.put("code", "101");
					argMap.put("msg", "失败");
				}
			}else{
				int heartstatus=hardwareInfoService.updateByMac(hwinfo);
				logger.info("update[根据mac心跳更新:]"+heartstatus);
				if(heartstatus>0){
					argMap.put("code", "100");
					argMap.put("msg", "成功");
				}else{
					argMap.put("code", "101");
					argMap.put("msg", "失败");
				}
			}
		}
		else if(cmd.equals("sendParkStatu")){//车位状态
			logger.info("cmd[车位状态推送指令:]"+cmd);
			net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(args.get("body"));
			System.out.print("json:"+json);
			String result = json.toString();
			JSONObject bodyJson = JSONObject.parseObject(result);
			Hardware hw=new Hardware();
			hw.setMac(String.valueOf(bodyJson.get("deviceID")));
			hw.setStatus(Integer.valueOf(String.valueOf(bodyJson.get("parkingStatu"))));
			hw.setDate(String.valueOf(bodyJson.get("time")));
			int ret = businessCarportService.updateBusinessCarportStatusYN(String.valueOf(hw.getMac()), hw.getStatus(), false);
			logger.info("updateBusinessCarportStatus resutl: " + ret);
			
			Activemq mq=new Activemq();
			int macId = hardwareService.macToIdyn(hw.getMac());
			BusinessCarport carport = businessCarportService.getBusinessCarportBymacId(macId);
			mq.setMac(hw.getMac());
			mq.setParkId(carport.getParkId());
			mq.setPortNumber(carport.getCarportNumber());
			if(hw.getStatus()==0){
				mq.setActionType("out");//离场
			}else if(hw.getStatus()==1){
				mq.setActionType("in");//入场
			}
			//mq.setActionType(null);
			mq.setChargeMoney(0.0);
			mq.setDiscount(0.0);
			mq.setEntranceDate("");
			mq.setExitDate("");
			mq.setId(0);
			mq.setIsLargeCar(0);
			mq.setLeftCount(0);
			mq.setOperatorId("");
			mq.setOther("");
			mq.setOutUrl("");
			mq.setOwner("");
			mq.setPaidMoney(0.0);
			mq.setParkDesc("");
			mq.setParkingType(2);
			mq.setPayType(0);
			mq.setPlateNumber("");
			mq.setPosId("");
			mq.setRejectReason("");
			mq.setUrl("");
			mq.setCmd("01001");//地磁
			
			if (ret > 0) {
				argMap.put("code", "100");
				argMap.put("msg", "成功");
				try {
					String url = "http://parkserver.iotclouddashboard.com/parkServer/mq/topicData";
					Gson gson=new Gson();
					String data=gson.toJson(mq);
					JSONObject jsons = JSON.parseObject(data);
					logger.info("json[转换后:]"+jsons);
					System.out.println("jsons:"+jsons);
					String parkId = jsons.get("parkId").toString();
					System.out.println("parkId:"+parkId);
					String mac = jsons.get("mac").toString();
					System.out.println("mac:"+mac);
					String portNumber=jsons.get("portNumber").toString();
					System.out.println("portNumber:"+portNumber);
					MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("mac",mac);
					jsonObject.put("topic",parkId);
					jsonObject.put("data",data);
					logger.info("activemq[发送数据:]"+jsonObject);
					
					String text = jsonObject.toJSONString();
					JSONObject jsonobj = JSONObject.parseObject(text);
					System.out.println("jsonobj:"+jsonobj);
					
					Request request = new Request.Builder()
							.url(url)
							.post(okhttp3.RequestBody.create(mediaType, jsonObject.toJSONString()))
							.build();
					OkHttpClient okHttpClient = new OkHttpClient();

					Call call = okHttpClient.newCall(request);
					call.enqueue(new Callback() {
						@Override
						public void onResponse(Call call, Response response) throws IOException {
							// TODO Auto-generated method stub
							logger.info("返回数据"+response.toString());
						}

						@Override
						public void onFailure(Call call, IOException e) {
							// TODO Auto-generated method stub
							logger.info("okHttpPost 请求错误:"+e.getMessage());
						}
					});

				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				argMap.put("code", "101");
				argMap.put("mag", "失败");
			}
			
			//新增
			/*int carportRet = 0;
			carportRet = businessCarportService.insertBusinessCarport(bus);
			if (carportRet > 0) {
				argMap.put("status", "1001");
				argMap.put("message", "insert businessCarport success");
				return Utility.gson.toJson(argMap);
			}else{
				argMap.put("status", "1002");
				argMap.put("message", "insert businessCarport fail, mac has already been used");
			}*/

			/*argMap.put("code", "100");
			argMap.put("msg", "成功");*/
			
		}
		return Utility.gson.toJson(argMap);
	}
	
}
